<template>
  <div class="login-container">
    <video src="../../assets/video/1.mp4" preload="auto" autoplay loop></video>
    <el-form
      :model="loginForm"
      status-icon
      :rules="rules"
      ref="loginForm"
      label-width="100px"
      class="login-loginForm"
    >
      <h1 class="title">RMB管理系统</h1>
      <!-- 角标 -->
      <div class="jiaobiao" @click="isErwei = !isErwei">
        <svg class="icon icon-jiao" aria-hidden="true">
          <use
            :xlink:href="
              isErwei ? '#icon-diannaojiaobiao' : '#icon-erweimajiaobiao'
            "
          ></use>
        </svg>
      </div>
      <!-- 二维码登入 -->
      <div class="erwei" v-if="isErwei">
        <div class="img">
          <img :src="qrImgUrl" width="200px" alt="" />
          <i class="mask" v-show="isScancode"> </i>
        </div>
        <p>请使用手机微信扫码登入</p>
      </div>
      <!-- 普通账号登入 -->
      <div class="input" v-else>
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="loginForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <!-- 验证码 -->
        <el-form-item label="验证码" prop="captcha">
          <el-input
            type="text"
            v-model="loginForm.captcha"
            @keydown.native.enter="submitForm('loginForm')"
            class="captcha"
            autocomplete="off"
          ></el-input>
          <span
            class="captcha-svg"
            @click="refreshCaptcha"
            v-html="captcha"
          ></span>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="submit"
            @click="submitForm('loginForm')"
            >登入</el-button
          >
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>
<script>
//引入socket.io客户端
import io from "socket.io-client";
//引入qrcode
import qr from "qrcode";

//引入vuex辅助函数

import { mapMutations } from "vuex";

import {
  loginApi,
  getCaptchaApi,
  verifyCaptchaApi,
  getQrcodeUrlApi,
  wechatLoginApi,
} from "@/api";
//1.收集用户的用户名和密码,发送给服务端

//2.服务端会进行校验,校验通过,返回用户信息和token

//3.将token存到本地存储

//4.登入成功需要跳转到主页

var validateUsn = (rule, value, callback) => {
  //用户名正则，3到16位（字母，数字，下划线，减号）
  var uPattern = /^[a-zA-Z0-9_-]{3,16}$/;
  if (uPattern.test(value)) {
    callback();
  } else {
    callback("3到16位(字母，数字，下划线，减号)");
  }
};

var validateCaptcha = (rule, value, callback) => {
  if (!value) {
    callback("验证码输入不能为空");
  } else {
    callback();
  }
};

var validatePsw = (rule, value, callback) => {
  if (!value) {
    callback("密码输入不能为空");
  } else {
    callback();
  }
};

export default {
  created() {
    //页面加载的时候 调用刷新验证码的方法
    this.refreshCaptcha();
  },
  data() {
    return {
      isErwei: false, //控制是否使用二维码扫码登入
      isScancode: false, //是否扫码
      qrImgUrl: "",
      loginForm: {
        username: "",
        password: "",
        captcha: "",
      },
      captcha: "",
      rules: {
        username: [{ validator: validateUsn, trigger: "blur" }],
        password: [{ validator: validatePsw, trigger: "blur" }],
        captcha: [{ validator: validateCaptcha, trigger: "blur" }],
      },
    };
  },
  methods: {
    ...mapMutations(["SET_USERINFO", "SET_USER_BUTTONS"]),
    //刷新验证码
    refreshCaptcha() {
      //发送请求 获取验证码
      getCaptchaApi().then((res) => {
        // console.log(res);
        this.captcha = res.data.img;
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //打开登入动画
          const loading = this.$loading({
            lock: true,
            text: "正在登入",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          //本地校验通过
          // console.log(this.loginForm);
          //1.校验验证码是否正确,如果正确再发送登入请求校验用户名
          //解构表单中的数据
          let { captcha, username, password } = this.loginForm;
          verifyCaptchaApi(captcha).then((res) => {
            // console.log(res);

            if (res.data.state) {
              //验证码通过,进行登入请求
              loginApi(username, password).then((res) => {
                // console.log(res);
                if (res.data.state) {
                  //登入成功
                  //将token存到本地
                  loading.close(); //关闭登入框动画
                  localStorage.setItem("qf-token", res.data.token);
                  localStorage.setItem(
                    "qf-userInfo",
                    JSON.stringify(res.data.userInfo)
                  );
                  //将用户的信息存到vuex中
                  // console.log(res);
                  this.SET_USERINFO(res.data.userInfo);
                  //用户的按钮存到vuex
                  this.SET_USER_BUTTONS(res.data.permission.buttons);
                  localStorage.setItem(
                    "permissionButtons",
                    JSON.stringify(res.data.permission.buttons)
                  );
                  //跳转到主页
                  this.$router.push("/");
                } else {
                  loading.close(); //关闭登入框动画
                  //登入失败
                  this.$message.error("用户名或者密码错误");
                }
              });
            } else {
              //不通过,提示错误
              this.$message.error("验证码输入错误,请重新输入");
              //重新刷新一个验证码
              this.refreshCaptcha();
              //清空验证码输入框的内容
              this.loginForm.captcha = "";
              loading.close(); //关闭登入框动画
            }
          });
        } else {
          //本地校验不通过
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  watch: {
    isErwei(newVal) {
      // console.log(newVal);//true是微信登入 false不是微信登入
      //判断用户是否切换到二维码登入
      //如果是二维码登入,那么我们需要使用scoket.io和服务器进行连接
      if (newVal === true) {
        let socket = io("ws://chst.vip");
        socket.on("connect", () => {
          console.log("连接成功");
          //调用接口,获取二维码地址(目的:将返回的地址,生成二维码)
          getQrcodeUrlApi().then((res) => {
            console.log(res);
            let qrUrl = res.data.scanCodeUrl; //获取了服务器返回的二维码地址
            //将二维码地址生成二维码
            qr.toDataURL(qrUrl, (err, imgUrl) => {
              if (err) throw err;
              // console.log(imgUrl);
              this.qrImgUrl = imgUrl;
              // console.log(this);
            });
          });
        });

        //扫码成功的事件
        socket.on("scancodeSuccess", (data) => {
          // console.log(data);服务端socket返回来的数据
          // console.log(7777);
          let { wechatCode } = data;
          this.isScancode = true;
          //微信登入
          wechatLoginApi(wechatCode).then((res) => {
            // this.$store.dispatch("FETCH_MENU_LIST")
            console.log(res);
            //登入成功
            //1.将token存到本地
            localStorage.setItem("qf-token", res.data.token);

            localStorage.setItem(
              "qf-userInfo",
              JSON.stringify(res.data.userInfo)
            );
            //将userInfo存到vuex中
            this.SET_USERINFO(res.data.userInfo);
            //用户的按钮存到vuex
            this.SET_USER_BUTTONS(res.data.permission.buttons);
            //按钮权限也存到localstroage
            localStorage.setItem(
              "permissionButtons",
              JSON.stringify(res.data.permission.buttons)
            );
            //2.将用户的信息也存到本地
            localStorage.setItem("userInfo", JSON.stringify(res.data.userInfo));
            //3.跳转到主页
            this.$router.push("/");
          });
        });
      }
    },
  },
};
</script>
<style scoped lang="less">
.login-container {
  width: 100%;
  height: 100%;
  video {
    position: fixed;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    //   width:100%;
    //   height: 100%;
  }
}
.login-loginForm {
  color: #fff;
  border-radius: 10px;
  width: 400px;
  height: 485px;
  position: fixed;
  background: rgba(0, 0, 0, 0.3);
  right: 100px;
  bottom: 80px;
  box-sizing: border-box;
  & /deep/ .el-input__inner {
    //深度选择器
    width: 250px;
  }

  & /deep/ .el-form-item {
    padding-right: 60px;
  }
  & /deep/ .el-button {
    width: 100%;
    background: linear-gradient(90deg, #1596fb, #002dff);
  }
  .title {
    margin: 20% 0;
  }
  & /deep/ .el-form-item__label {
    color: #fff;
  }
  /deep/ .el-form-item__error {
    color: #2ce866;
  }
  .jiaobiao {
    width: 60px;
    height: 60px;
    position: absolute;
    right: 2px;
    top: 2px;
    cursor: pointer;
  }
  .icon-jiao {
    width: 100%;
    height: 100%;
  }
  //二维码样式
  .erwei .img {
    display: inline-block;
    position: relative;
    width: 200px;
    height: 200px;
    img {
      position: absolute;
      left: 0;
    }
    .mask {
      width: 100%;
      height: 100%;
      opacity: 0.8;
      background-color: #fff;
      position: absolute;
      left: 0;
      background-image: url("../../assets/imgs/scancode.png");
      background-size: 50%;
      background-repeat: no-repeat;
      background-position: center;
    }
  }
}
/deep/ .el-form-item__content {
  width: 250px !important;
}
.captcha {
  width: 100px;
  vertical-align: top;

  & /deep/ .el-input__inner {
    width: 100%;
    height: 45px;
    border-radius: 5px 0 0 5px;
    border: 0;
    font-size: 18px;
  }
}
svg path {
  stroke: red;
}
.captcha-svg {
  background: #fff;
  display: inline-block;
  height: 45px;
  width: 150px;
  text-align: center;
  cursor: pointer;
  border: 0;
  border-radius: 0px 5px 5px 0;
}
</style>
